package com.cyandpos.pad.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.changyi.device.DatePattern;
import com.cyandpos.pad.R;
import com.cyandpos.pad.common.commondata.BaseResponse;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.cateringformat.morefunction.adapter.OrderFoodtableGridAdapter;
import com.cyandpos.pad.cateringformat.morefunction.bean.OrderfoodInput;
import com.cyandpos.pad.cateringformat.morefunction.bean.Table;
import com.cyandpos.pad.cateringformat.morefunction.bean.TableData;
import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.ToastUtils;
import com.google.gson.JsonObject;
import com.google.zxing.common.StringUtils;
import com.landicorp.android.eptapi.utils.StringUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class OrderFoodActivity extends AppCompatActivity {
    private TextView tv_dialogtitle_name;
    private OrderFoodtableGridAdapter foodtableGridAdapter;
    private GridView gridView;
    private  Button clear_exit_btn;
    private AlertDialog mDialog;//所有dialog
    private List<Table> tablelist;
    private ProgressDialog mWaitDialog;

   public static int arrive_year;
   public static int arrive_month;
   public static int arrive_day;
   public static int arrive_hour;
   public static int arrive_min;
    /*
       1.查询没有预定过的桌子
    *  2.点击条目预定 调接口更新状态
    *  3.转态更新完 重新调接口 把最新的刷新 桌子状态查询出来  。已经预定的桌子 状态带出来 给桌子加个颜色 并且不可在点击 。或者是可以取消  预定
    *
    * */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_food);
        tv_dialogtitle_name= findViewById(R.id.tv_dialog_title_name);
        gridView= findViewById(R.id.gv_act_ordertable);
        tablelist = new ArrayList<>();
        updataTable();
        mWaitDialog = new ProgressDialog(OrderFoodActivity.this);
        tv_dialogtitle_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        foodtableGridAdapter = new OrderFoodtableGridAdapter(OrderFoodActivity.this,tablelist);
        gridView.setAdapter(foodtableGridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                foodtableGridAdapter.setSelectPos(position, true);

                //调接口 改变桌子状态
                input_YD_Dialog(position);

            }
        });
    }

    private void updataTable() {

        PosHttpManager.querytablesHttpEexcute(0,new OkHttpUtils.ResultCallback() {
            @Override
            public void onSuccess(JsonObject response) {
                Log.i("TAG----桌子列表： ",response.toString());
                BaseResponse<TableData> baseResponse = BaseResponse.fromJson(response.toString(), TableData.class);
                if(baseResponse.getCode().equals("0")){
                    tablelist.clear();
                    if (baseResponse.getData().getData()!=null){
                        tablelist.addAll(baseResponse.getData().getData());
                        foodtableGridAdapter.notifyDataSetChanged();
                    }else {
                        ToastUtils.showMsg("没有可预定桌子");
                    }

                }else{
                    ToastUtils.showMsg("返回数据不正确："+baseResponse.getMsg());
                }

            }
            @Override
            public void onFailure(String msg) {
                ToastUtils.showMsg("异常："+msg);

            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        tv_dialogtitle_name.setText("请选择预定的桌号");
    }

    /**
     *  预定信息录入
     * @param position
     */
    private void input_YD_Dialog(final int position) {
        //dialog_table_clear_layout.xml
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_ordertable_input, null);
        final EditText et_ordertable_size = (EditText) view.findViewById(R.id.et_ordertable_size_input);
        final EditText ordertable_user = (EditText) view.findViewById(R.id.et_ordertable_user_input);
        final EditText et_ordertable_phone = (EditText) view.findViewById(R.id.et_ordertable_phone_input);
         final TextView et_ordertable_data = (TextView) view.findViewById(R.id.et_ordertable_data_input); //年月日
         final EditText et_ordertable_time = (EditText) view.findViewById(R.id.et_ordertable_endtime_input); // 具体时间
        String yyyyMMdd = DatePattern.mDateFormat3.format(new Date());
      //  String HHmmss = DatePattern.mDateFormat30.format(new Date());
      //  Log.i("TAG-----时间",time);
     //   et_ordertable_data.setText(yyyyMMdd);
      //  et_ordertable_time.setText(HHmmss);

        final TextView title_name = (TextView) view.findViewById(R.id.tv_dialog_title_name);
        Button ordertableOK = (Button) view.findViewById(R.id.et_ordertable_ok);
        Button ordertableNo = (Button) view.findViewById(R.id.et_ordertable_no);
        title_name.setText("请填写预定客人信息");

        et_ordertable_data.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {

                View view = View.inflate(getApplicationContext(), R.layout.new_act_date_time_picker_title, null);
                final DatePicker datePicker = (DatePicker)view.findViewById(R.id.new_act_date_picker);
                final TimePicker timePicker = (TimePicker)view.findViewById(R.id.new_act_time_picker);

                // Init DatePicker
                int year;
                int month;
                int day;

              /*  if (et_ordertable_data.getText().toString().isEmpty()) {
                    // Use the current date as the default date in the picker
                    final Calendar c = Calendar.getInstance();
                    year = c.get(Calendar.YEAR);
                    month = c.get(Calendar.MONTH);
                    day = c.get(Calendar.DAY_OF_MONTH);
                } else {
                    year = OrderFoodActivity.arrive_year;
                    month = OrderFoodActivity.arrive_month;
                    day = OrderFoodActivity.arrive_day;

                }*/

                final Calendar c = Calendar.getInstance();
                year = c.get(Calendar.YEAR);
                month = c.get(Calendar.MONTH);
                day = c.get(Calendar.DAY_OF_MONTH);
                datePicker.init(year, month, day, null);

                // Init TimePicker
                int hour;
                int minute;
               /* if (et_ordertable_phone.getText().toString().isEmpty()) {
                    // Use the current time as the default values for the picker
                    final Calendar c1 = Calendar.getInstance();
                    hour = c1.get(Calendar.HOUR_OF_DAY);
                    minute = c1.get(Calendar.MINUTE);
                } else {
                    hour = OrderFoodActivity.arrive_hour;
                    minute = OrderFoodActivity.arrive_min;
                }*/
                final Calendar c1 = Calendar.getInstance();
                hour = c1.get(Calendar.HOUR_OF_DAY);
                minute = c1.get(Calendar.MINUTE);

                timePicker.setIs24HourView(true);
                timePicker.setCurrentHour(hour);
                timePicker.setCurrentMinute(minute);

                // Build DateTimeDialog
                AlertDialog.Builder builder = new AlertDialog.Builder(OrderFoodActivity.this);
                builder.setView(view);
                 //builder.setTitle("时间选择器");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        arrive_year = datePicker.getYear();
                        arrive_month = datePicker.getMonth();
                        arrive_day = datePicker.getDayOfMonth();
                       // String dateStr = DateUtil.formatDate(arrive_year, arrive_month, arrive_day);
                       // arriveDateBtn.setText(dateStr);
                        String format = String.format("%d-%02d-%02d", arrive_year, arrive_month + 1, arrive_day);


                        arrive_hour = timePicker.getCurrentHour();
                        arrive_min = timePicker.getCurrentMinute();
                       // String timeStr = DateUtil.formatTime(arrive_hour, arrive_min);
                        //    arriveTimeBtn.setText(timeStr); "2021-09-08 10:51:16
                        et_ordertable_data.setText(format+" " +arrive_hour+":"+arrive_min+":00");
                      //  et_ordertable_data.setText(arrive_year+"-"+arrive_month+"-"+arrive_day+" " +arrive_hour+":"+arrive_min+":00");

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                       dialog.dismiss();
                    }
                });
                builder.show();


            }
        });

       //  et_ordertable_endtime.setText(time);

        ordertableNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        title_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });

        ordertableOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CommonUtils.isNullOrEmpty(CommonUtils.getContent(et_ordertable_size))){
                    ToastUtils.showMsg("预定人数不能为空！");
                    return;
                }
                if(CommonUtils.isNullOrEmpty(CommonUtils.getContent(ordertable_user))){
                    ToastUtils.showMsg("联系人不能为空！");
                    return;
                }
                if(CommonUtils.isNullOrEmpty(CommonUtils.getContent(et_ordertable_phone))){
                    ToastUtils.showMsg("手机号不能为空！");
                    return;
                }
                if(CommonUtils.isNullOrEmpty(CommonUtils.getContent(et_ordertable_data))){
                    ToastUtils.showMsg("预定开始日期不能为空！");
                    return;
                }
                /*if(CommonUtils.isNullOrEmpty(CommonUtils.getContent(et_ordertable_time))){
                    ToastUtils.showMsg("预定具体时间不能为空！");
                    return;
                }*/
                mDialog.dismiss();
                showWaitDialog("正在预定餐桌");
                OrderfoodInput orderfoodInput =  new OrderfoodInput();
                orderfoodInput.setMealsCount(et_ordertable_size.getText().toString());
                orderfoodInput.setId(tablelist.get(position).getId());
                orderfoodInput.setShopid(tablelist.get(position).getShopid());
                orderfoodInput.setName(ordertable_user.getText().toString());
                orderfoodInput.setPhone(et_ordertable_phone.getText().toString());
                orderfoodInput.setBeginTime(et_ordertable_data.getText().toString()+et_ordertable_time.getText().toString());

                 PosHttpManager.reserveTableHttpEexcute(orderfoodInput, new OkHttpUtils.ResultCallback() {
                     @Override
                     public void onSuccess(JsonObject response) {
                           Log.i("TAG----预定状态后返回",response.toString());
                         dismissWaitDialog();

                         BaseResponse<Object> baseResponse = BaseResponse.fromJson(response.toString(), TableData.class);

                         if(baseResponse.getCode().equals("0")){
                             ToastUtils.showMsg("预定成功");
                             updataTable(); //预定后重新更新
                         }else{
                             ToastUtils.showMsg(""+baseResponse.getMsg().toString());
                         }
                     }
                     @Override
                     public void onFailure(String msg) {
                         ToastUtils.showMsg("预定接口异常:"+msg);

                     }
                 });

                //mSalePresenterImpl.preparePay(mTicketInfo,djdData,ysDateList,exchangeGoodBillInfoList,giftGoodsBillList);
            }
        });
        AlertDialog.Builder builder = new AlertDialog.Builder(OrderFoodActivity.this);
        builder.setView(view).setCancelable(false).create();
        mDialog = builder.show();

    }

    public void showWaitDialog(String msg) {
        mWaitDialog.setCancelable(false);
        if (mWaitDialog != null && !mWaitDialog.isShowing()) {
            mWaitDialog.setMessage(msg);
            mWaitDialog.show();
        }
    }

    public void dismissWaitDialog() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
        }
    }


}
